#pragma once

#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"
#include "InetAddr.hpp"


using namespace LogModule;

const static std::string defaultdic = "./dictionary.txt";
const static std::string sep = ":";

class Dict
{
    public:
    Dict(std::string dict_path = defaultdic)
        :_dict_path(dict_path)
    {

    }

    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::FATAL) <<"打开文件失败" ;
            return false;
        }

        std::string line;
        while(std::getline(in , line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::ERROR) << line << "解析失败";
                continue;
            }

            std::string english = line.substr(0 , pos);
            std::string chinese = line.substr(pos);
            if(english.empty() || chinese.empty())
            {
                LOG(LogLevel::ERROR) << line << "没有有效内容" <<line;
                continue;
            }
            _dict.insert(std::make_pair(english , chinese));
        }
        LOG(LogLevel::DEBUG) << "加载: " << line;
        in.close();
        return true;
    }

    std::string Translate(std::string word )
    {
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入翻译但没有找到" << word;
            return nullptr;
        }

        LOG(LogLevel::DEBUG) << "进入翻译找到了"  << word;
        return iter->second;
    }
    ~Dict()
    {

    }
    private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _dict_path;
};